<?php

require('pagina.php');
require('database.php');
require('auth.php');
require('core.php');

// Verifica se esta autenticado com pelo menos nivel 3
validaPermissao(3);

// Pega data do proximo pagamento de labor
$next_duedate = query_fetch("SELECT next_duedate FROM period_duedates WHERE id=1");
$next_duedate = strtotime($next_duedate['next_duedate']);

// Verifica se houve comando para lancar labor expenses:
if (isset($_GET['labor']) && ($next_duedate == NULL || $_SERVER['REQUEST_TIME'] > $next_duedate))
{
	// Verifica se o lancamento do labor dos funcionarios esta nulo
	if ($next_duedate == NULL)
	{
		$ultima_quinzena = getdate(fim_ultima_quinzena()); // pega data atual

		$dia = $ultima_quinzena['mday']+1;
		$mes = $ultima_quinzena['mon'];
		$ano = $ultima_quinzena['year'];

		if ($dia != 16)
		{
			$dia = 1;
			$mes++;
			if ($mes == 13)
			{
				$ano ++;
				$mes = 1;
			}
		}

		query_bd("UPDATE period_duedates SET next_duedate='{$ano}-{$mes}-{$dia}' WHERE id=1");
		$next_duedate = strtotime("{$ano}-{$mes}-{$dia}");
	}

	// Se o dia atual eh maior que o dia do fechamento do labor.. calcula labors
	if ($_SERVER['REQUEST_TIME'] > $next_duedate)
	{
		$payday = getdate($next_duedate);
		$dia = $payday['mday'];
		$mes = $payday['mon'];
		$ano = $payday['year'];

		$to = strtotime("{$ano}-{$mes}-" . ($dia-1));

		// Coloca data no dia do pagamento a partir da data do ultimo fechamento de labor
		if ($dia == 1)
		{
			$dia = 7;

			$from = strtotime("{$ano}-" . ($mes-1) . "-16");
		}
		else if ($dia == 16)
		{
			$dia = 22;

			$from = strtotime("{$ano}-{$mes}-01");
		}

		// Calcula e soma labor de todos os funcionarios
		$employees = query_bd("SELECT employees.id, contacts.name FROM employees, contacts".
			" WHERE employees.contact_id=contacts.id");
		while ($employee = mysql_fetch_array($employees))
		{
			$labor = calculateLabor($employee['id'], $from, $to);

			// Cria duedate do period duedate
			if ($labor['labor_expense'] != 0)
				query_bd("INSERT INTO duedates VALUES " .
				"(NULL, 'Labor expense', '{$labor['labor']} hours of {$employee['name']}', ". LABOR .
				", '{$ano}-{$mes}-{$dia}', " .
				"{$labor['labor_expense']}, FALSE, " . EMPLOYEE . ", {$employee['id']}, NULL, NULL)");
			unset($employee);
		}
		unset($employees);

		// Coloca a data no proximo dia de fechamento de labor, a partir deste dia de pagamento
		if ($dia == 7)
			$dia = 16;
		else if ($dia == 22)
		{
			$dia = 1;
			$mes++;
			if ($mes == 13)
			{
				$ano ++;
				$mes = 1;
			}
		}

		// Atualiza period duedate de labor com o novo next duedate
		query_bd("UPDATE period_duedates SET next_duedate='{$ano}-{$mes}-{$dia}' WHERE id=1");
		$next_duedate = strtotime("{$ano}-{$mes}-{$dia}");
	}
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Incomes and Expenses');
adicionar_css('incomes_expenses.css');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
adicionar_js('toggle.js');
pagina_head();

// Pega o nome e id de todas as locacoes
$locations = array();
$resultado = query_bd("SELECT locations.id, contacts.name FROM locations, contacts " .
	"WHERE locations.locationcontact=contacts.id AND locations.operating=TRUE " .
	"ORDER BY contacts.name");
while ($loc = mysql_fetch_array($resultado))
	$locations[] = $loc;
unset($resultado);

// Opcoes
echo "<ul id=opcoes>";
echo "<li class='positive'><a href='income_new.php'><img src='img/add.png' alt=''>New Income</a></li>";
echo "<li class='positive'><a href='expense_new.php'><img src='img/add.png' alt=''>New Expense</a></li>";
echo "<li><a href='incomes_expenses.php?",
	(isset($_GET['from'])? "&amp;from={$_GET['from']}" : ""),
	(isset($_GET['to'])? "&amp;to={$_GET['to']}" : ""),
	(isset($_GET['employee'])? "&amp;employee={$_GET['employee']}" : ""),
	(isset($_GET['customer'])? "&amp;customer={$_GET['customer']}" : ""),
	(@$_GET['location']? "&amp;location=" . @$_GET['location'] : ""),
	(isset($_GET['report'])? "&amp;report={$_GET['report']}" : ""),
	(isset($_GET['event'])? "&amp;event={$_GET['event']}" : ""),
	(isset($_GET['contact'])? "&amp;contact={$_GET['contact']}" : ""),
	"&amp;print=1' target='_blank' ><img src='img/print.png' alt=''>Print</a></li>";
echo "</ul><br><br>";

// Formulario para limitar o periodo de tempo
echo "<form id=periodo method=GET action=incomes_expenses.php>";
if (isset($_GET['employee']))
	echo "<input type=HIDDEN name=employee value={$_GET['employee']}>";
if (isset($_GET['customer']))
	echo "<input type=HIDDEN name=customer value={$_GET['customer']}>";
if (@$_GET['location'])
	echo "<input type=HIDDEN name=location value={$_GET['location']}>";
if (isset($_GET['report']))
	echo "<input type=HIDDEN name=report value={$_GET['report']}>";
if (isset($_GET['event']))
	echo "<input type=HIDDEN name=event value={$_GET['event']}>";
if (isset($_GET['contact']))
	echo "<input type=HIDDEN name=contact value={$_GET['contact']}>";
echo "<label for=from>From:</label> <input id=from type=TEXT value='" . @$_GET['from'] . "' name='from' size=9>" .
	"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'from', 'chooserSpan1', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
	"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
echo "<label for=to>To:</label> <input id=to type=TEXT value='" . @$_GET['to'] . "' name='to' size=9>" .
	"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'to', 'chooserSpan2', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
	"<div id='chooserSpan2' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
echo "<input type=SUBMIT value='submit' name='ok'><br>";
echo "<strong>Filters:</strong><br>";
echo "<label for=inc_category>Incomes:</label> <select id=inc_category name=inc_category>";
echo "<option value=all>All</option>";
echo "<option value=none", (@$_GET['inc_category']=='none'? " selected=SELECTED" : ""), ">None</option>";
foreach ($INC_CATEGORIES as $num => $nome)
	echo "<option value={$num}", (@$_GET['inc_category']=="$num"? " selected=SELECTED" : ""), ">{$nome}</option>";
echo "</select>";

echo "<label for=exp_category>Expenses:</label> <select id=exp_category name=exp_category>";
echo "<option value=all>All</option>";
echo "<option value=none", (@$_GET['exp_category']=='none'? " selected=SELECTED" : ""), ">None</option>";
foreach ($EXP_CATEGORIES as $num => $nome)
	echo "<option value={$num}", (@$_GET['exp_category']== "$num"? " selected=SELECTED" : ""), ">{$nome}</option>";
echo "</select><br>";

echo "<label for=location>Subjects to location:</label> <select id=location name='location' >";
echo "<option value=0 >----any----</option>";
foreach ($locations as $loc)
	echo	"<option value={$loc['id']} ", (@$_GET['location']==$loc['id']? "selected=SELECTED" : ""), ">{$loc['name']}</option>";
unset($locations);
echo "</select><br>";

echo "</form><br>";

/* Gets time period */
$from = (@$_GET['from']? strtotime($_GET['from']) : inicio_ultima_quinzena());
$to = (@$_GET['to']? strtotime($_GET['to']) : fim_ultima_quinzena());

// Mostra tabela com os dados
echo "<table id=incomes_expenses>";
echo "<caption><em>Incomes and Expenses",
($from? " from " . date("M j Y", $from) : ""),
($to? " until " . date("M j Y", $to) : "");

if (isset($_GET['employee']))
{
	$employee = query_fetch("SELECT contacts.name FROM contacts, employees WHERE " .
		"contacts.id=employees.contact_id AND employees.id={$_GET['employee']}");
	echo " concerning the employee <a href='employee.php?id={$_GET['employee']}'>{$employee['name']}</a>";
}
else if (isset($_GET['customer']))
{
	$customer = query_fetch("SELECT contacts.name FROM contacts, customers WHERE " .
		"contacts.id=customers.contact_id AND customers.id={$_GET['customer']}");
	echo " concerning the customer <a href='customer.php?id={$_GET['customer']}'>{$customer['name']}</a>";
}
else if (@$_GET['location'])
{
	$location = query_fetch("SELECT contacts.name FROM contacts, locations WHERE " .
		"contacts.id=locations.locationcontact AND locations.id=" . $_GET['location'] );
	echo " concerning the location <a href='location.php?id={$_GET['location']}'>{$location['name']}</a>";
}
else if (isset($_GET['report']))
{
	$report = query_fetch("SELECT reportdate FROM reports WHERE id={$_GET['report']}");
	echo " concerning the <a href='report.php?id={$_GET['report']}'>report</a> from",
		date("M j Y", $report['name']);
}

echo "</em></caption>";

$TOTAL_INCOME = 0.0;
$TOTAL_EXPENSE = 0.0;

if (@$_GET['inc_category'] != 'none')
{
	$incomes = query_bd("SELECT * FROM duedates WHERE value>0" .
		($from? " AND UNIX_TIMESTAMP(payday) >= {$from}" : "") .
		($to? " AND UNIX_TIMESTAMP(payday) <= {$to}" : "") .
		(isset($_GET['employee'])? " AND references_to=". EMPLOYEE . " AND reference_id={$_GET['employee']}" : "") .
		(isset($_GET['customer'])? " AND references_to=". CUSTOMER . " AND reference_id={$_GET['customer']}" : "") .
		(@$_GET['location']? " AND references_to=". LOCATION . " AND reference_id=" . @$_GET['location'] : "") .
		(isset($_GET['report'])? " AND references_to=". REPORT . " AND reference_id={$_GET['report']}" : "") .
		(isset($_GET['event'])? " AND references_to=". EVENT . " AND reference_id={$_GET['event']}" : "") .
		(isset($_GET['contact'])? " AND references_to=". CONTACT . " AND reference_id={$_GET['contact']}" : "") .
		(is_numeric(@$_GET['inc_category'])? " AND category=" . @$_GET['inc_category'] : "")
		. " ORDER BY payday");

	echo "<tr><td><table id=incomes><caption><em>", mysql_affected_rows(), " Incomes</em></caption>";
	echo "<tr><th>Date<th>Name<th>Category<th>Value";

	while ($income = mysql_fetch_array($incomes))
	{
		flush();	/* Manda o que ja tem em buffer para o cliente */

		echo "<tr><td>", date("M j Y", strtotime($income['payday'])),
			"<td><a href='income.php?id={$income['id']}'>{$income['name']}</a><br>",
			$income['description'], "<td>", $INC_CATEGORIES[$income['category']], "<td>",
			($income['paid'] == FALSE? "<img src='img/hand.png' alt='(pending)'>" : ""), show_money($income['value']);

		$TOTAL_INCOME += $income['value'];
		unset($income);
	}
	echo "<tr><th><th><th><th>", show_money($TOTAL_INCOME);
	echo "</table>";
	unset($incomes);

	$period_incomes = query_bd("SELECT * FROM period_duedates WHERE value>0 AND id>1" .
		(isset($_GET['employee'])? " AND references_to=" . EMPLOYEE . " AND reference_id={$_GET['employee']}" : "") .
		(isset($_GET['customer'])? " AND references_to=" . CUSTOMER . " AND reference_id={$_GET['customer']}" : "") .
		(@$_GET['location']? " AND references_to=" . LOCATION . " AND reference_id=" . @$_GET['location'] : "") .
		(isset($_GET['report'])? " AND references_to=" . REPORT . " AND reference_id={$_GET['report']}" : "") .
		(isset($_GET['event'])? " AND references_to=" . EVENT . " AND reference_id={$_GET['event']}" : "") .
		(isset($_GET['contact'])? " AND references_to=" . CONTACT . " AND reference_id={$_GET['contact']}" : "") .
		(is_numeric(@$_GET['inc_category'])? " AND category=" . @$_GET['inc_category'] : ""));

	// Mostrar period duedates incomes
	echo "<em><a href=\"javascript:toggle('period_incomes')\" >Period Incomes(", mysql_affected_rows(), ")</a></em>";
	echo "<table id=period_incomes style='display: none'>";
	echo "<tr><th>Period<th>Name<th>Category<th>Value";
	while ($period_income = mysql_fetch_array($period_incomes))
	{
		echo "<tr><td>", $DUEDATESPERIODS[$period_income['period']],
			"<td><a href='period_income.php?id={$period_income['id']}'>{$period_income['name']}</a><br>",
			$period_income['description'], "<td>", $INC_CATEGORIES[$period_income['category']], "<td>",
			show_money($period_income['value']);
		unset($period_income);
	}
	echo "</table>";
	unset($period_incomes);
}

if (@$_GET['exp_category'] != 'none')
{
	$expenses = query_bd("SELECT * FROM duedates WHERE value<0" .
		($from? " AND UNIX_TIMESTAMP(payday) >= {$from}" : "") .
		($to? " AND UNIX_TIMESTAMP(payday) <= {$to}" : "") .
		(isset($_GET['employee'])? " AND references_to=" . EMPLOYEE . " AND reference_id={$_GET['employee']}" : "") .
		(isset($_GET['customer'])? " AND references_to=" . CUSTOMER . " AND reference_id={$_GET['customer']}" : "") .
		(@$_GET['location']? " AND references_to=" . LOCATION . " AND reference_id=" . @$_GET['location'] : "") .
		(isset($_GET['report'])? " AND references_to=" . REPORT . " AND reference_id={$_GET['report']}" : "") .
		(isset($_GET['event'])? " AND references_to=" . EVENT . " AND reference_id={$_GET['event']}" : "") .
		(isset($_GET['contact'])? " AND references_to=" . CONTACT . " AND reference_id=" . @$_GET['contact'] : "") .
		(is_numeric(@$_GET['exp_category'])? " AND category={$_GET['exp_category']}" : "")
		. " ORDER BY payday");

	echo "<td><table id=expenses ><caption><em>", mysql_affected_rows(), " Expenses</em></caption>";
	echo "<tr><th>Date<th>Name<th>Category<th>Value";

	while ($expense = mysql_fetch_array($expenses))
	{
		flush();	/* Manda o que ja tem em buffer para o cliente */

		echo "<tr><td>", date("M j Y", strtotime($expense['payday'])),
			"<td><a href='expense.php?id={$expense['id']}'>{$expense['name']}</a><br>",
			$expense['description'], "<td>", $EXP_CATEGORIES[$expense['category']], "<td>",
			($expense['paid'] == FALSE? "<img src='img/hand.png' alt='(pending)'>" : ""), show_money($expense['value']);

		$TOTAL_EXPENSE += $expense['value'];
		unset($expense);
	}
	echo "<tr><th><th><th><th>", show_money($TOTAL_EXPENSE);
	echo "</table>";
	unset($expenses);

	$period_expenses = query_bd("SELECT * FROM period_duedates WHERE value<0 AND id>1" .
		(isset($_GET['employee'])? " AND references_to=" . EMPLOYEE . " AND reference_id={$_GET['employee']}" : "") .
		(isset($_GET['customer'])? " AND references_to=" . CUSTOMER . " AND reference_id={$_GET['customer']}" : "") .
		(@$_GET['location']? " AND references_to=" . LOCATION . " AND reference_id=" . @$_GET['location'] : "") .
		(isset($_GET['report'])? " AND references_to=" . REPORT . " AND reference_id={$_GET['report']}" : "") .
		(isset($_GET['event'])? " AND references_to=" . EVENT . " AND reference_id={$_GET['event']}" : "") .
		(isset($_GET['contact'])? " AND references_to=" . CONTACT . " AND reference_id={$_GET['contact']}" : "") .
		(is_numeric(@$_GET['exp_category'])? " AND category=" . @$_GET['exp_category'] : ""));

	// Mostrar period duedates expenses
	echo "<em><a href=\"javascript:toggle('period_expenses')\" >Period Expenses(", mysql_affected_rows(), ")</a></em>";
	echo "<table id=period_expenses style='display: none'>";
	echo "<tr><th>Period<th>Name<th>Category<th>Value";
	while ($period_expense = mysql_fetch_array($period_expenses))
	{
		echo "<tr><td>", $DUEDATESPERIODS[$period_expense['period']],
			"<td><a href='period_expense.php?id={$period_expense['id']}'>{$period_expense['name']}</a><br>",
			$period_expense['description'], "<td>", $EXP_CATEGORIES[$period_expense['category']], "<td>",
			show_money($period_expense['value']);
		unset($period_expense);
	}
	echo "</table>";
	unset($period_expenses);
}

echo "</table>";

// Mostra algumas conclusoes gerais
$BALANCE = $TOTAL_INCOME + $TOTAL_EXPENSE;
echo "<hr><ul class=resumo_total>";
echo "<li><strong>Balance:</strong> ", show_money($BALANCE), "</li>";
echo "</ul>";

// Verifica se ha opcao de fechar o labor da quinzena
if ($next_duedate == NULL || $_SERVER['REQUEST_TIME'] > $next_duedate && !isset($_GET['print']))
{
	echo "<div id=calculate_labor><a href='incomes_expenses.php?labor=ok' ",
	" onClick='return confirm(\"Do you really want to close the previous fortnight labor?\");'>",
	"Calculate labor expense of previous fortnight: ",
	date("M j Y", inicio_ultima_quinzena()), " to ", date("M j Y", fim_ultima_quinzena()),
	"</a></div>";
}

// Finaliza pagina
pagina_fim();
?>
